<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\Material as MaterialService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;

class OrderMaterial extends Base
{
    /**
     * @var \app\mp\admin\PurchasingV2
     */
    public $controller;

    /**
     * 根据订单ID获取材料列表
     *
     * @param integer $orderId
     * @param string|array $materialType
     * @param string $field
     * @return array
     * @author KING
     * @date 2020年7月1日
     *
     */
    public function getListByOrderId($orderId, $materialType = '', $field = '*',$clientOrdernum='')
    {
        $info = db('order_material')->where('mid', substr($clientOrdernum, 1, 100))->field($field)->find();
        if (substr($clientOrdernum, 0, 1) == 'B' && !empty($info['material_id']) ) { //如果是备货查询
            $materialService = new MaterialService();
            $mInfo = $materialService->getInfoById($info['material_id']);
            $result = [];
            if (empty($materialType) || is_array($materialType) && in_array($mInfo['type'], $materialType) || $materialType == $mInfo['type']) {
                $result = [];
                $result[0] = $info;
                $result[0]['mInfo'] = $mInfo;
            }
            return $result;
        }
        if (empty($orderId)) return [];
        $order = "caichuang_standard desc";
        $orderRaw="FIELD(m.type,'fabric','lining','accessories'),m.supplier asc";
        $list = db('order_material om')->where('order_id', $orderId)
            ->join('material m', "om.material_id=m.id", 'left')
            ->where('material_id', '>', 0)->order($order)->orderRaw($orderRaw)->field("om.*")->select();
        $materialService = new MaterialService();
        $n = 0;
        $result = [];
        foreach ($list as $k => $v) {
            $mInfo = $materialService->getInfoById($v['material_id']);
            if (empty($mInfo)) continue;
            if (empty($materialType) || is_array($materialType) && in_array($mInfo['type'], $materialType) || $materialType == $mInfo['type']) {
                $result[$n] = $v;
                $result[$n]['mInfo'] = $mInfo;
                $n++;
            }
        }
        return $result;
    }

    /**
     * 根据订单ID获取材料列表（裁剪进度使用）
     *
     * @param integer $orderId
     * @param string|array $materialType
     * @param string $field
     * @return array
     * @author KING
     * @date 2020年7月1日
     *
     */
    public function getListByOrderIdForCutting($orderId, $materialType = ['fabric', 'lining'], $field = '*')
    {
        if (empty($orderId)) return [];
        $list = db('order_material')->where('order_id', $orderId)->where('material_id', '>', 0)->field($field)->select();
        $materialService = new MaterialService();
        $n = 0;
        $result = [];
        foreach ($list as $k => $v) {
            $mInfo = $materialService->getInfoById($v['material_id']);
            if (empty($mInfo)) continue;
            if ($materialType == '' || is_array($materialType) && in_array($mInfo['type'], $materialType) || $materialType == $mInfo['type']) {
                if ($materialService->checkIsIncludeKeys($mInfo['name'])) continue;

                $result[$n] = $v;
                $result[$n]['mInfo'] = $mInfo;
                $n++;
            }
        }
        return $result;
    }

    /**
     * 检测订单在裁床后是否进入配料仓库
     * 规则：检测所有辅料是否都含有关键字（朴、透明条、织带、橡筋），如都含有则直接进入车间不进入配料仓库
     *
     * @param integer $orderId 订单ID
     * @author King
     * @date 2020年9月3日
     *
     */
    public function checkNeedDistributing($orderId)
    {
        $materialService = new MaterialService();
        $list = $this->getListByOrderId($orderId, 'accessories', 'material_id');
        foreach ($list as $v) {
            if (!$materialService->checkIsIncludeKeys($v['mInfo']['name'], 'accessories')) {    // 如果至少有一个不含有指定关键词，则需要进入配料仓库
                return true;
            }
        }
        return false;
    }

    /**
     * 根据ID获取记录信息
     *
     * @param integer $id
     * @param string $field
     * @return array
     * @author KING
     * @date 2020年7月9日
     *
     */
    public function getInfoById($id, $field = '*')
    {
        if (empty($id)) return [];
        $materialService = new MaterialService();
        $orderSizeService = new OrderSizeService();
        $info = db('order_material')->where('mid', $id)->field('*')->findOrEmpty();
        if (!empty($info['order_id'])) {
            $osList = $orderSizeService->getListByOrderId($info['order_id']);
            $info['shicai_count'] = $shicaiCount = array_sum(array_column($osList, 'shicai_count'));
            $info['custom_simple_cost_2'] = sprintf("%.2f", $info['customer_dosage'] * $info['customer_price'] * (1 + $info['loss'] / 100));//客户单件成本 客户用量（MES不含损耗）*客户单价+损耗
            $disscount_pic = $info['fabric_price_amount'] + $info['dosage_price_amount'];// 面料核价增加金额 + 用量核价增加
            $info['col1_2'] = round(($info['custom_simple_cost_2'] + $disscount_pic) * $info['shicai_count'], 2); //客户物料总金额
            $info['win_money'] = sprintf("%.2f", round($info['col1_2'] - $info['caigou_subtotal_money'], 2));
        }
        if ($info && isset($info['material_id'])) {
            $info['mInfo'] = $materialService->getInfoById($info['material_id']);
        }
        return $info;
    }

    /**
     * 根据订单ID和物料ID获取行记录
     *
     * @param integer $orderId
     * @param integer $materialId
     * @param string $field
     * @return array
     * @author KING
     * @date 2020年7月9日
     *
     */
    public function getInfoByOrderIdMaterialId($orderId, $materialId, $field = '*', $mid = 0)
    {
        if ($mid > 0) {
            $info = db('order_material')->where('mid', $mid)->field($field)->findOrEmpty();
            $materialService = new MaterialService();
            if ($info && isset($info['material_id'])) {
                $info['mInfo'] = $materialService->getInfoById($info['material_id']);
            }
            return $info;
        }
        if (empty($orderId) || empty($materialId)) return [];
        $info = db('order_material')->where('order_id', $orderId)->where('material_id', $materialId)->field($field)->findOrEmpty();
        $materialService = new MaterialService();
        if ($info && isset($info['material_id'])) {
            $info['mInfo'] = $materialService->getInfoById($info['material_id']);
        }
        return $info;
    }

    /**
     * 检查是否可裁床
     * @param integer $orderid
     */
    public function checkCanCaiChuang($orderId)
    {
        $list = $this->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
        if (empty($list)) return true;
        //$maxCustomerDosage = max(array_column($list, 'customer_dosage'));	// 最大客户用量
        foreach ($list as $k => $v) {
            if ($v['caigou_show'] == 0) continue;
            if (in_array($v['caigou_status'], [0, 2])) return false;
            else {
                //$orderMaterialItemService = new OrderMaterialItemService();

                // 验布缩水是否都已完成（20200915取消验布缩水校验）
                // if (!$orderMaterialItemService->checkCheckclothShrinkOver($v['order_id'], $v['material_id'])) return false;
            }
        }
        return true;
    }

    /**
     * 获取客户用量最大的mid
     *
     * @param integer $orderId
     * @return integer
     * @author King
     * @date 2020年9月1日
     *
     */
    public function getMaxCustomerDosageMid($orderId)
    {
        $list = $this->getListByOrderIdForCutting($orderId, ['fabric', 'lining']);
        if (empty($list)) return 0;

        $lastMid = 0;
        $maxCustomerDosage = 0;
        foreach ($list as $v) {
            if ($v['customer_dosage'] > $maxCustomerDosage) {
                $maxCustomerDosage = $v['customer_dosage'];
                $lastMid = $v['mid'];
            }
        }
        return $lastMid;
    }

    /**
     * 设置裁床基准物料（客户用量最大的物料）
     *
     * @param integer $orderId
     * @param number $mid
     * @return boolean
     * @author King
     * @date 2020年9月1日
     *
     */
    public function setCaichuangStandard($orderId, $mid = 0)
    {
        if ($mid == 0) {
            $mid = $this->getMaxCustomerDosageMid($orderId);
        }
        if ($mid > 0) {
            db('order_material')->where('order_id', $orderId)->update(['caichuang_standard' => 0]);
            db('order_material')->where('mid', $mid)->update(['caichuang_standard' => 1]);
            //以基准面料颜色为准 更新订单的款型颜色
            $material_id=db('order_material')->where('mid', $mid)->value("material_id",0);
            $materialColor=db("material")->find($material_id);
            if(!empty($materialColor['color'])){
                db('order')->where('id', $orderId)->update(['dress_color' => $materialColor['color']]);
            }
        }
        return true;
    }

    /**
     * 检查采购状态是否全部批色完成
     * @param integer $orderid
     */
    public function checkCaiGouStatus($orderId)
    {
        $list = $this->getListByOrderId($orderId);
        foreach ($list as $k => $v) {
            if ($v['caigou_show'] == 0) continue;
            if ($v['mInfo']['type'] == 'accessories') continue;
            if (in_array($v['caigou_status'], [0, 2])) return false;
        }
        return true;
    }

    /**
     * 计算订单的采购合计金额
     * @param integer $orderId
     * @author KING  date 2016-1-13
     *
     */
    public function getAllCaigouSubtotalMoney($orderId)
    {
        if (empty($orderId)) return 0;
        $where = [
            ['order_id', '=', $orderId]
        ];
        return db('order_material')->where($where)->sum('caigou_subtotal_money');
    }

    /**
     * 重新计算唛架信息(应裁数)
     *
     * @param integer $mid
     * @author King
     * @date 2020年9月2日
     *
     */
    public function resetWheatData($mid)
    {
        if (empty($mid)) return false;
        $omInfo = $this->getInfoById($mid);
        if (empty($omInfo)) return false;

        $orderMaterialItemService = new OrderMaterialItemService();
        $omiList = $orderMaterialItemService->getListByOrderMaterialId($mid);

        // 重新计算应裁数
        $caichuangWheatLow = array_sum(array_column($omiList, 'caichuang_wheat_low'));    // 低层数
        $caichuangWheatHeight = array_sum(array_column($omiList, 'caichuang_wheat_height'));    // 高层数
        $yingcaiCount = ceil($caichuangWheatLow * $omInfo['caichuang_wheat_low_number']) + ceil($caichuangWheatHeight * $omInfo['caichuang_wheat_height_number']);
        $upData = [
            'caichuang_wheat_low' => $caichuangWheatLow,
            'caichuang_wheat_height' => $caichuangWheatHeight,
            'yingcai_count' => $yingcaiCount,
        ];
        db('order_material')->where('mid', $mid)->update($upData);
        return true;
    }

    /**
     * 获取某个材料的需用量
     *
     * @param integer $orderId
     * @param integer $materialId
     * @return number
     * @author KING
     * @date 2020年7月22日
     *
     */
    public function getNeedDosage($orderId, $materialId)
    {
        $quantity = db('order')->where('id', $orderId)->value('quantity', 0);
        $materialDosage = db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->value('material_dosage', 0);
        return $quantity * $materialDosage;
    }

    /**
     * 获取物料状态
     *
     * @param integer $mid
     * @author King
     * @date 2020年10月13日
     *
     */
    public function getMaterialStatus($mid)
    {
        $omInfo = $this->getInfoById($mid);
        $result = [
            'is_make_tag' => $omInfo['is_make_tag'],//是否打标
            'is_caigou_start' => $omInfo['is_caigou_start'],    // 采购状态（0未开始，1采购中，2采购完成）
            'is_checkcloth' => $omInfo['need_checkcloth'],    // 验布状态（0无需验布，1验布未完成，2验布完成）
            'is_shrink' => $omInfo['need_shrink'],    // 缩水状态（0无需缩水，1缩水未完成，2缩水完成）
            'material_return' => 0 // 换料状态（0无换料，1换料中，2换料完成）
        ];

        // 检测是否验布完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_checkcloth']) {
            if (db('order_material_item')->where('order_material_id', $mid)->where('is_checkcloth', 0)->where('is_return', 0)->count() == 0) $result['is_checkcloth'] = 2;
        }
        // 检测是否缩水完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_shrink']) {
            if (db('order_material_item')->where('order_material_id', $mid)->where('is_shrink', 0)->where('is_return', 0)->count() == 0) $result['is_shrink'] = 2;
        }

        // 换料状态
        if (db('material_return')->where('order_material_id', $mid)->where('status', '<=', 1)->count()) $result['material_return'] = 1;
        elseif (db('material_return')->where('order_material_id', $mid)->where('is_renew', 1)->where('status', '<>', 1)->count()) $result['material_return'] = 2;
        elseif (db('material_return')->where('order_material_id', $mid)->where('is_renew', 1)->count()) $result['material_return'] = 1;

        return $result;
    }

    public function getMaterialStatusV2($omInfo)
    {
        $result = [
            'is_make_tag' => $omInfo['is_make_tag'],//是否打标
            'is_caigou_start' => $omInfo['is_caigou_start'],    // 采购状态（0未开始，1采购中，2采购完成）
            'is_checkcloth' => $omInfo['need_checkcloth'],    // 验布状态（0无需验布，1验布未完成，2验布完成）
            'is_shrink' => $omInfo['need_shrink'],    // 缩水状态（0无需缩水，1缩水未完成，2缩水完成）
            'material_return' => 0,// 换料状态（0无换料，1换料中，2换料完成）
        ];

        // 检测是否验布完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_checkcloth'] == 1 && $omInfo['cloth_0'] == $omInfo['tiaoshu']) {
            $result['is_checkcloth'] = 2;
        }
        // 检测是否缩水完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_shrink'] == 1 && $omInfo['cloth_1'] == $omInfo['tiaoshu']) {
            $result['is_shrink'] = 2;
        }
        // 换料状态
//        if ($omInfo['material_return_0'] > 0) {
//            $result['material_return'] = 1;
//        } elseif ($omInfo['material_return_1'] > 0) {
//            $result['material_return'] = 2;
//        } elseif ($omInfo['material_return_2'] > 0) {
//            $result['material_return'] = 1;
//        }
        return $result;
    }

    /**
     * 更新物料和订单的可裁剪状态
     * @param integer $orderId
     * @param integer $orderMaterialId
     */
    public function updateCaichuangStatus($orderId, $orderMaterialId = 0)
    {

        if ($orderMaterialId == 0) {
            $omList = $this->getListByOrderIdForCutting($orderId);
            foreach ($omList as $key => $value) {
                $omInfo = $this->getInfoById($value['mid']);
                $materialStatus = $this->getMaterialStatus($value['mid']);
                if ($omInfo['mInfo']['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2 && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $materialStatus['material_return'] != 1 && $omInfo['caigou_status'] == 1) {
                    db('order_material')->where('mid', $value['mid'])->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
                } else {
                    db('order_material')->where('mid', $value['mid'])->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
                }
            }
        } else {
            $omInfo = $this->getInfoById($orderMaterialId);
            $materialStatus = $this->getMaterialStatus($orderMaterialId);
            if ($omInfo['mInfo']['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2 && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $materialStatus['material_return'] != 1 && $omInfo['caigou_status'] == 1) {
                db('order_material')->where('mid', $orderMaterialId)->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
            } else {
                db('order_material')->where('mid', $orderMaterialId)->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
            }
        }
        if ($this->checkCaichangCanDoStatus($orderId)) {
            db('order')->where('id', $orderId)->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
        } else {
            db('order')->where('id', $orderId)->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
        }
    }

    /**
     * 更新物料和订单的可裁剪状态
     * @param integer $orderId
     * @param integer $orderMaterialId
     */
    public function updateCaichuangStatusV2($orderId, $orderMaterialId = 0, $obj = null)
    {
        if ($orderMaterialId == 0) {
            $omList = $this->get_order_material_list([$orderId]);
            foreach ($omList as $key => $omInfo) {
                $materialStatus = $omInfo['material_status'];
                if ($omInfo['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2 && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $omInfo['tiaoshu_status'] != 10 && $omInfo['caigou_status'] == 1) {
                    db('order_material')->where('mid', $omInfo['mid'])->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
                    $obj != null && $obj->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[{$omInfo['name']}（mid {$omInfo['mid']}）]可裁剪");
                } else {
                    db('order_material')->where('mid', $omInfo['mid'])->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
                }
            }
        } else {
            $omList = $this->get_order_material_list([], [$orderMaterialId]);
            $omInfo = $omList[0];
            if($omInfo['stock_m_type']==1){
                return $this->updateCaichuangStatusV2_stock_m_type_1($omInfo,$obj);
            }
            $materialStatus = $omInfo['material_status'];
            if ($omInfo['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2 && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $omInfo['tiaoshu_status'] != 10 && $omInfo['caigou_status'] == 1) {
                db('order_material')->where('mid', $orderMaterialId)->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
                $obj != null && $obj->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[{$omInfo['name']}（mid {$omInfo['mid']}）]可裁剪");
            } else {
                db('order_material')->where('mid', $orderMaterialId)->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
            }
        }
        if ($this->checkCaichangCanDoStatus($orderId)) {
            db('order')->where('id', $orderId)->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
            $obj != null && $obj->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "整单可裁剪");
        } else {
            db('order')->where('id', $orderId)->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
        }
    }

    public function updateCaichuangStatusV2_stock_m_type_1($omInfo, $obj)
    {
        $materialStatus = $omInfo['material_status'];
        if ($omInfo['type'] != 'accessories' && $materialStatus['is_make_tag'] == 1 && $materialStatus['is_caigou_start'] == 2 && $materialStatus['is_checkcloth'] != 1 && $materialStatus['is_shrink'] != 1 && $omInfo['tiaoshu_status'] != 10 && $omInfo['caigou_status'] == 1) {
            db('order_material')->where('mid', $omInfo['mid'])->update(['caichuang_can_do' => 1, 'caichuang_can_do_time' => time(), 'update_time' => time()]);
            $obj != null && $obj->addOrderLog(0, '', "物料[{$omInfo['name']}（mid {$omInfo['mid']}）]可裁剪", ['type' => 1, 'order_material_id' => $omInfo['mid']]);
            return true;
        } else {
            db('order_material')->where('mid', $omInfo['mid'])->update(['caichuang_can_do' => 0, 'caichuang_can_do_time' => 0, 'update_time' => time()]);
            return false;
        }
    }

    /**
     * 获取订单的材料信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/13
     */
    public function get_order_material_list($order_id_array = [], $mids = [])
    {
        $where = [
            ['om.material_id', '>', 0],
            ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
        ];
        if ($order_id_array != []) {
            $where[] = ['om.order_id', 'in', $order_id_array];
        }
        if ($mids != []) {
            $where[] = ['om.mid', 'in', $mids];
        }
        $list_order_material = db('order_material om')
            ->field("om.mid,om.order_id,om.client_ordernum,om.material_id,om.stock_m_type,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.tiaoshu_status,om.caigou_status,om.tiaoshu
                ,om.arrive_time,om.caigou_over_time,om.caichuang_can_do
                ,m.name,m.type,m.color
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_checkcloth=1 and mi.is_return=0, mi.id,null)) as cloth_0
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_shrink=1 and mi.is_return=0, mi.id,null)) as cloth_1
                ")
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('stock_log sl', "m.type='accessories' and om.material_id=sl.material_id and om.order_id=sl.order_id", 'left')
            ->join('material_stock ms', "om.material_id=ms.material_id and ms.cutting_time=0", 'left')
            ->join('material_stock_use msu', "om.order_id=msu.order_id and om.material_id=msu.material_id", 'left')
            ->join('order_material_item mi', "om.order_id=mi.order_id and om.material_id=mi.material_id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->where($where)
            ->order('om.caichuang_standard desc')
            ->group('om.mid')
            ->select();
        foreach ($list_order_material as $k2 => $sv) {
            $list_order_material[$k2]['material_status'] = $this->getMaterialStatusV2($sv);
        }
        return $list_order_material;
    }

    /**
     * 检查订单状态裁剪状态是否可更新
     * @param integer $orderId
     * @param integer $orderMaterialId
     */
    public function checkCaichangCanDoStatus($orderId)
    {
        $omList = $this->getListByOrderIdForCutting($orderId);
        foreach ($omList as $k => $v) {
            if ($v['caichuang_can_do'] == 0) return FALSE;
        }
        return true;
    }

    /**
     * 检测订单某物料是否需要验布缩水 物料进度是否显示
     *
     * @param integer $orderId
     * @param integer $materialId
     * @return array
     * @author King
     * @date 2021年3月8日
     *
     */
    public function checkNeedCheckclothShrink($orderId, $materialId)
    {
        $materialTags = db('material_tags')->order('id desc')->select();

        // 根据物料表判断物料是否需要验布缩水（优先1）
        $materialInfo = db('material')->find($materialId);
        $needCheckcloth = $materialInfo['need_checkcloth'];
        $needShrink = $materialInfo['need_shrink'];

        // 根据物料标签库匹配是否需要验布缩水及采购进度显示（优先2）
        $caigouShow = 1;
        foreach ($materialTags as $tv) {
            if (mb_stripos($materialInfo['name'], trim($tv['name'])) !== false) {
                if ($needCheckcloth == 2) $needCheckcloth = $tv['need_checkcloth'];
                if ($needShrink == 2) $needShrink = $tv['need_shrink'];
                $caigouShow = $tv['caigou_show'];
                break;
            }
        }

        // 根据返单判断（优先3）
        $sku = db('order')->where('id', $orderId)->value('sku');
        if ($needCheckcloth == 2 || $needShrink == 2) {
            $orderIdsHistory = db('order')->where('sku', $sku)->where('id', '<', $orderId)->column('id');
            $omReorderInfo = db('order_material')->where('order_id', 'in', $orderIdsHistory)->order('mid desc')->field('need_checkcloth,need_shrink')->find();
            if ($needCheckcloth == 2) $needCheckcloth = arrayGet($omReorderInfo, 'need_checkcloth', 0);
            if ($needShrink == 2) $needShrink = arrayGet($omReorderInfo, 'need_shrink', 0);
        }
        return [
            'need_checkcloth' => $needCheckcloth,
            'need_shrink' => $needShrink,
            'caigou_show' => $caigouShow,
        ];
    }

    /**
     * 检查验布是否亏损
     * @param integer $mid
     * @param integer $orderMaterialId
     */
    public function checkClothLossStatus($mid)
    {
        $orderService = new OrderService();
        $count = db('order_material_item')->where("order_material_id=" . $mid . " and is_checkcloth=0")->count();
        if ($count > 0) return false;
        $omInfo = $this->getInfoById($mid, "billing_caigou_count,checkcloth_length,material_id,order_id,client_ordernum");
        if ($omInfo['billing_caigou_count'] == 0 || $omInfo['checkcloth_length'] == 0) return false;
        if (floatval(($omInfo['billing_caigou_count'] - $omInfo['checkcloth_length']) / $omInfo['billing_caigou_count']) > config('mp.check_cloth_control')) {
            $oeData = [
                'material_id' => $omInfo['material_id'],
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'type' => 1,
                'desc' => '验布-物料亏损严重',
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time()
            ];
            db('order_exception')->insert($oeData, true);
            $orderService->updateExceptionNum($omInfo['order_id']);//更新订单物料异常次数
            return round(($omInfo['billing_caigou_count'] - $omInfo['checkcloth_length']), 2);
        }
        return false;
    }

    /**
     * 检查缩水是否亏损1
     * @param integer $mid
     * @param integer $orderMaterialId
     */
    public function checkShrinkLossStatus1($mid)
    {
        $orderService = new OrderService();
        $count = db('order_material_item')->where("order_material_id=" . $mid . " and is_shrink=0")->count();
        if ($count > 0) return false;
        $omInfo = $this->getInfoById($mid, "billing_caigou_kgcount,weight_shrink,weight_page,material_id,order_id,client_ordernum");
        $netWeight = $omInfo['weight_shrink'] - $omInfo['weight_page'];
        if ($omInfo['billing_caigou_kgcount'] == 0 || $netWeight == 0) return false;
        if (floatval(($omInfo['billing_caigou_kgcount'] - $netWeight) / $omInfo['billing_caigou_kgcount']) > config('mp.shrink_control1')) {
            $oeData = [
                'material_id' => $omInfo['material_id'],
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'type' => 2,
                'desc' => '缩水重量-物料亏损严重',
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time()
            ];
            db('order_exception')->insert($oeData, true);
            $orderService->updateExceptionNum($omInfo['order_id']);//更新订单物料异常次数
            return round(($omInfo['billing_caigou_kgcount'] - $netWeight), 2);
        }
        return false;
    }

    /**
     * 检查缩水是否亏损2
     * @param integer $mid
     * @param integer $orderMaterialId
     */
    public function checkShrinkLossStatus2($mid)
    {
        $orderService = new OrderService();
        $count = db('order_material_item')->where("order_material_id=" . $mid . " and is_shrink=0")->count();
        if ($count > 0) return false;
        $omInfo = $this->getInfoById($mid, "billing_caigou_kgcount,weight_shrink,weight_page,material_id,order_id,client_ordernum,tiaoshu");
        $where = [
            ['order_id', '=', $omInfo['order_id']],
            ['material_id', '=', $omInfo['material_id']],
            ['type', '=', 2]
        ];
        $trueWeight = db('checkcloth_shrink')->where($where)->value("sum(true_weight)");


        if ($omInfo['tiaoshu'] == 0 || $trueWeight == 0) return false;
        $vWeight = $trueWeight / $omInfo['tiaoshu'];
        if (floatval($vWeight - $omInfo['mInfo']['weight']) > config('mp.shrink_control2')) {
            $oeData = [
                'material_id' => $omInfo['material_id'],
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'type' => 3,
                'desc' => '缩水克重-物料亏损严重',
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time()
            ];
            db('order_exception')->insert($oeData, true);
            $orderService->updateExceptionNum($omInfo['order_id']);//更新订单物料异常次数
            return round(($vWeight - $omInfo['mInfo']['weight']), 2);
        }
        return false;
    }

    /**
     * 检查裁床是否亏损1
     * @param integer $mid
     * @param integer $orderMaterialId
     */
    public function checkCaichuangLossStatus1($mid)
    {
        $orderService = new OrderService();
        $orderSizeService = new OrderSizeService();
        $omInfo = db('order_material')->where("mid=" . $mid . " and caichuang_over_time!=0")->field("yingcai_count,material_id,order_id,client_ordernum")->findOrEmpty();
        if (!$omInfo) return false;
        $osList = $orderSizeService->getListByOrderId($omInfo['order_id']);
        $shicaiCount = array_sum(array_column($osList, 'shicai_count'));
        if ($shicaiCount == 0 || $omInfo['yingcai_count'] == 0) return false;
        if (floatval($omInfo['yingcai_count'] - $shicaiCount) > config('mp.caichuang_control1')) {
            $oeData = [
                'material_id' => $omInfo['material_id'],
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'type' => 4,
                'desc' => '裁剪数量-物料亏损严重',
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time()
            ];
            db('order_exception')->insert($oeData, true);
            $orderService->updateExceptionNum($omInfo['order_id']);//更新订单物料异常次数
            return round(($omInfo['yingcai_count'] - $shicaiCount), 2);
        }
        return false;
    }

    /**
     * 检查裁床是否亏损2
     * @param integer $mid
     * @param integer $orderMaterialId
     */
    public function checkCaichuangLossStatus2($mid)
    {
        $orderService = new OrderService();
        $orderSizeService = new OrderSizeService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $materialStockCuttingService = new MaterialStockCuttingService();
        $omInfo = db('order_material')->where("mid=" . $mid . " and caichuang_over_time!=0")->field("yingcai_count,material_id,order_id,client_ordernum,return_length,caichuang_strip_dosage,caichuang_wheat_height_length,caichuang_wheat_low_length")->findOrEmpty();
        if (!$omInfo) return false;
        $osList = $orderSizeService->getListByOrderId($omInfo['order_id']);
        $shicaiCount = array_sum(array_column($osList, 'shicai_count'));
        $mscInfo = $materialStockCuttingService->getInfoByMaterialId($omInfo['order_id'], $omInfo['material_id']);
        $omiList = $orderMaterialItemService->getListByOrderMaterialId($mid);
        $caichuangBefore = array_sum(array_column($omiList, 'length')) + arrayGet($mscInfo, 'length', 0) - $omInfo['return_length'];
        $heightTotal = array_sum(array_column($omiList, 'caichuang_t_wheat_height')) + arrayGet($mscInfo, 'caichuang_t_wheat_height', 0);
        $lowTotal = array_sum(array_column($omiList, 'caichuang_t_wheat_low')) + arrayGet($mscInfo, 'caichuang_t_wheat_height', 0);
        $neadendTotal = array_sum(array_column($omiList, 'caichuang_t_neadend')) + arrayGet($mscInfo, 'caichuang_t_neadend', 0);
        $stripTotal = array_sum(array_column($omiList, 'caichuang_t_strip')) + arrayGet($mscInfo, 'caichuang_t_strip', 0);
        $allStripDosage = $omInfo['caichuang_strip_dosage'] * $shicaiCount;
        $caichuangAfter = $labuLenght = round(($heightTotal * $omInfo['caichuang_wheat_height_length']) + ($lowTotal * $omInfo['caichuang_wheat_low_length']) + $neadendTotal + $stripTotal + $allStripDosage + ($heightTotal + $lowTotal) * 0.06, 2);//拉布米长

        if ($caichuangAfter == 0 || $caichuangBefore == 0) return false;
        if (floatval(($caichuangBefore - $caichuangAfter) / $caichuangBefore) > config('mp.caichuang_control2')) {
            $oeData = [
                'material_id' => $omInfo['material_id'],
                'order_id' => $omInfo['order_id'],
                'client_ordernum' => $omInfo['client_ordernum'],
                'type' => 5,
                'desc' => '裁剪总计-物料亏损严重',
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time()
            ];
            db('order_exception')->insert($oeData, true);
            $orderService->updateExceptionNum($omInfo['order_id']);//更新订单物料异常次数
            return round(($caichuangBefore - $caichuangAfter), 2);
        }
        return false;
    }

    /**
     * 退料设置
     * 如在换料中，引发母单的采购状态修改即order表的caigou_status caigou_over_time的设置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/13
     */
    public function material_return_update($mid = 0, $materialReturnId = 0)
    {
        if ($mid == 0) {
            $materialReturn_info = db('material_return')->whereRaw("id={$materialReturnId}")->find();
            switch ($materialReturn_info['stock_m_type']) {
                case 1:
                    $omInfo = db('order_material')->where([
                        ['mid', '=', $materialReturn_info['order_material_id']],
                    ])->find();
                    $mid = $omInfo['mid'];
                    break;
                case 0:
                    $omInfo = db('order_material')->where([
                        ['order_id', '=', $materialReturn_info['order_id']],
                        ['material_id', '=', $materialReturn_info['material_id']],
                    ])->find();
                    $mid = $omInfo['mid'];
                    break;
            }
        } else {
            $omInfo = db('order_material')->where('mid', $mid)->find();
        }
        if ($omInfo['tiaoshu'] < 1) {
            throw new \Exception('条数不能为负');
            return false;
        }
        $tiaoshu_status = 0;//条数状态  0未知 10条数由正变0时的状态  11为最终为正的状态
        $omInfo['tiaoshu'] > 0 && $omInfo['tiaoshu'] - 1 == 0 && $tiaoshu_status = 10;
        $omData = [
            'tiaoshu' => $omInfo['tiaoshu'] - 1,
            'shiji_caigou_count' => $omInfo['tiaoshu'] - 1,
            'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
            'tiaoshu_status' => $tiaoshu_status,
            'tiaoshu_status_time' => time(),
            'update_time' => time(),
        ];
        db('order_material')->where('mid', $mid)->update($omData);
        if ($tiaoshu_status == 10) {//条数为0时，采购状态也变为没完成
            $orderData = [];
//            $orderData['update_time'] = time();
//            $orderData['caigou_user_id'] = 0;
            $orderData['caigou_status'] = 0;
//            $orderData['caigou_over_time'] = 0;
            db('order')->where('id', $omInfo['order_id'])->update($orderData);
            $this->updateCaichuangStatusV2(0, $mid);//更新物料和订单的可裁剪状态
            $this->update_caigou_status([$mid], 0, []);//更新采购状态，批色状态
        }
        $this->update_caigou_status([], 0, [$omInfo['order_id']]);//更新采购状态，批色状态
        return true;
    }

    /**
     * 退料设置--换料中处理
     * @param int $materialReturnId
     * @return bool
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/14
     */
    public function material_return_update_tuiliao($materialReturnId = 0)
    {
        $materialReturn_info = db('material_return')->whereRaw("id={$materialReturnId}")->find();
        $omInfo = db('order_material')->where([
            ['order_id', '=', $materialReturn_info['order_id']],
            ['material_id', '=', $materialReturn_info['material_id']],
        ])->find();
        $mid = $omInfo['mid'];
        if ($omInfo['tiaoshu_status'] != 10) {
            $omData = [
                'is_caigou_start'=>1,
                'tiaoshu_status' => 10,
                'tiaoshu_status_time' => time(),
                'update_time' => time(),
            ];
            db('order_material')->where('mid', $mid)->update($omData);
        }
        $this->updateCaichuangStatusV2(0, $mid);//更新物料和订单的可裁剪状态
        return true;
    }

    /**
     * 更新采购状态，批色状态
     * 更新order表与order_material表的采购状态
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/27
     */
    public function update_caigou_status($mids = [], $status = 0, $order_ids = [])
    {
        //1,修正order_material表的采购状态
        if ($mids != []) {
            $list = db('order_material om')
                ->field("om.mid,om.order_id,om.tiaoshu,om.caigou_first_time")
                ->join('material m', "om.material_id=m.id", 'left')
                ->where([
                    ['om.mid', 'in', $mids],
                    ['om.material_id', '>', 0],
                    ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
                    ['m.type', '<>', 'accessories'],
                ])->select();
            foreach ($list as $k => $v) {
                $oud = array(
                    'update_time' => time(),
                    'caigou_status' => $status,//是否批色（0为否，1为是，2批色不通过）
                    'caigou_over_time' => $status == 1 ? time() : 0,
                );
                if ($v['caigou_first_time'] == 0) {
                    $oud['caigou_first_time'] = time();
                }
                db('order_material')->where('mid', '=', $v['mid'])->update($oud);
                $order_ids[] = $v['order_id'];
            }
        }
        //2,修正order表的采购状态，面里料的caigou_status=1，0 2引发order表caigou_status的修改
        if ($order_ids == []) {
            return true;
        }
        $list = db('order_material om')->field("om.mid,om.order_id,om.caigou_status,om.tiaoshu,om.caigou_first_time,om.caigou_over_time")
            ->join('material m', "om.material_id=m.id", 'left')
            ->where([
                ['om.order_id', 'in', $order_ids],
                ['om.caigou_show', '<>', 0],
                ['om.material_id', '>', 0],
                ['m.type', '<>', 'accessories'],
            ])->order('om.caigou_over_time asc')->select();
        $res_list = [];
        foreach ($list as $k => $v) {
            $res_list[$v['order_id']][] = $v;
        }
        $order_update = [];
        foreach ($res_list as $k => $v) {
            $flag = 0;
            foreach ($v as $k2 => $v2) {
                $order_update[$k]['update_time'] = time();
                ADMIN_ID > 0 && $order_update[$k]['caigou_user_id'] = ADMIN_ID;
                if ($v2['caigou_status'] == 1 && $v2['tiaoshu'] > 0) {//批色，且条数>0，才是采购完成--暂时采购完成
                    $order_update[$k]['caigou_status'] = 1;
                    $order_update[$k]['caigou_over_time'] = $v2['caigou_over_time'] > 0 ? $v2['caigou_over_time'] : time();
                } else {
                    $flag = 1;
                    $order_update[$k]['caigou_status'] = 0;
                    $order_update[$k]['caigou_over_time'] = 0;
                    break;
                }
            }
            if ($flag == 1) {
                $order_update[$k]['caigou_status'] = 0;
                $order_update[$k]['caigou_over_time'] = 0;
            }
        }
        foreach ($order_update as $k => $v) {
            $info = db('order')->field('id,status')->where('id', $k)->find();
            ($info['status'] == 0) && $v['status'] = 1;
            db('order')->where('id', $k)->update($v);
        }
        return $order_update;
    }

    /**
     * 更新采购状态，批色状态
     * 更新order表与order_material表的采购状态
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/27
     */
    public function update_caigou_status_old($mids = [], $status = 0, $order_ids = [])
    {
        //1,修正order_material表的采购状态
        if ($mids != []) {
            $list = db('order_material')->field("mid,order_id,tiaoshu,caigou_first_time")
                ->where([
                    ['mid', 'in', $mids],
                    ['material_id', '>', 0],
                    ['caigou_show', '<>', 0],// 去除不在采购进度显示条目
                ])->select();
            foreach ($list as $k => $v) {
                if ($status == 1 && $v['tiaoshu'] <= 0) {//条数为0 不能批色通过
                    $order_update[$k]['caigou_status'] = 0;
                    $order_update[$k]['caigou_over_time'] = 0;
                    return $order_update;
                }
                $oud = array(
                    'update_time' => time(),
                    'caigou_status' => $status,//是否批色（0为否，1为是，2批色不通过）
                    'caigou_over_time' => $status == 1 ? time() : 0,
                );
                if ($v['caigou_first_time'] == 0) {
                    $oud['caigou_first_time'] = time();
                }
                db('order_material')->where('mid', '=', $v['mid'])->update($oud);
                $order_ids[] = $v['order_id'];
            }
        }
        //2,修正order表的采购状态，面里料的caigou_status=1，0 2引发order表caigou_status的修改
        if ($order_ids == []) {
            return true;
        }
        $list = db('order_material om')->field("om.mid,om.order_id,om.caigou_status,om.tiaoshu,om.caigou_first_time,om.caigou_over_time")
            ->join('material m', "om.material_id=m.id", 'left')
            ->where([
                ['om.order_id', 'in', $order_ids],
                ['om.caigou_show', '<>', 0],
                ['om.material_id', '>', 0],
                ['m.type', '<>', 'accessories'],
            ])->order('om.caigou_over_time asc')->select();
        $res_list = [];
        foreach ($list as $k => $v) {
            $res_list[$v['order_id']][] = $v;
        }
        $order_update = [];
        foreach ($res_list as $k => $v) {
            $flag = 0;
            foreach ($v as $k2 => $v2) {
                $order_update[$k]['update_time'] = time();
                ADMIN_ID > 0 && $order_update[$k]['caigou_user_id'] = ADMIN_ID;
                if ($v2['caigou_status'] == 1) {
                    $order_update[$k]['caigou_status'] = 1;
                    $order_update[$k]['caigou_over_time'] = $v2['caigou_over_time'] > 0 ? $v2['caigou_over_time'] : time();
                } else {
                    $flag = 1;
                    $order_update[$k]['caigou_status'] = 0;
                    $order_update[$k]['caigou_over_time'] = 0;
                }
                if ($v2['tiaoshu'] <= 0) {//条数为0 采购就是没完成
                    $flag = 1;
                    $order_update[$k]['caigou_status'] = 0;
                    $order_update[$k]['caigou_over_time'] = 0;
                    break;
                }
            }
            if ($flag == 1) {
                $order_update[$k]['caigou_status'] = 0;
                $order_update[$k]['caigou_over_time'] = 0;
            }
        }
        foreach ($order_update as $k => $v) {
            $info = db('order')->field('id,status')->where('id', $k)->find();
            ($info['status'] == 0) && $v['status'] = 1;
            db('order')->where('id', $k)->update($v);
        }
        return $order_update;
    }

    /**
     * 到料操作记录--连带 按没开始采购的按钮   --针对新数据处理
     * 1，如arrive_time>0 ,则arrive_time_first不操作 ，也不记录 到料日志
     * 2,返回值为 1时 是实际到料按钮处理。要 记录 到料日志
     * @param $obj
     * @param $mid
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/16
     */
    public function arriveTime(&$obj, $mid)
    {
        $info = db('order_material om')->field("om.mid,om.order_id,om.client_ordernum,om.material_id,om.stock_m_type
        ,m.name
        ,om.arrive_time,om.arrive_time_first,om.is_caigou_start ")
            ->join('order o', "om.order_id=o.id", 'left')
            ->join('material m', "om.material_id=m.id", 'left')
            ->where([
                ['om.mid', '=', $mid],
            ])
            ->find();
        if ($info['arrive_time'] > 0) {
            $result = db('order_material')->where('mid', $mid)->update(['arrive_time' => time()]);
            return ['num' => 100, 'info' => $info];
        }
        $result = db('order_material')->where('mid', $mid)->update([
            'arrive_time' => time(),
            'arrive_time_first' => time(),
        ]);
        //连带 按没开始采购的按钮
        if ($info['is_caigou_start'] == 0) {
            $this->startPurchasing($obj, $info['order_id'], $info['material_id'],$info);
        }
        $obj->addOrderLog($info['order_id'], $info['client_ordernum'], "物料[{$info['name']}（mid {$info['mid']}）]到料");
        return ['num' => 1, 'info' => $info];
    }

    /**
     * 开始采购
     * @author KING zhuguosen后封装 @date 2022/5/16
     * @date 2020年6月3日
     */
    public function startPurchasing(&$obj, $orderId = 0, $materialId = 0,$minfo=[])
    {
        if ($orderId > 0) {//原采购，但去除了查库存
            $orderService = new OrderService();
            $orderInfo = $orderService->getInfoById($orderId);
            $materialName = getMaterialName($materialId);
            db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update(['is_caigou_start' => 1, 'caigou_start_time' => time()]);
            $obj->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$materialName}（material_id {$materialId}）]开始采购");
            return ['ret' => 1, 'msg' => '采购中'];
        }
        if ($minfo != [] && $minfo['stock_m_type'] == 1) {
            db('order_material')->where(['mid' => $minfo['mid']])->update(['is_caigou_start' => 1, 'caigou_start_time' => time()]);
            $obj->addOrderLog(0, '', "物料[{$minfo['name']}（material_id {$minfo['material_id']}）]开始采购", ['type' => 1, 'order_material_id' => $minfo['mid']]);
            return ['ret' => 1, 'msg' => '采购中'];
        }
    }

    /**
     * 新增采购任务
     * @param $param
     * @return int|string
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/17
     */
    public function addCaigouMaterial($param)
    {
        $materialInfo = db('material')->find($param['material_id']);
        $orderMaterial = [
            'order_id' => 0,
            'client_ordernum' => '',
            'material_id' => $param['material_id'],
            'stock_m_type' => 1,//库存物料类型,0常规订单料,1备料
            'need_num' => $param['need_num'],//还需用量--备料类型下使用
            'caigou_unitprice' => $materialInfo['price'], // 采购单价 目前直接使用  客户单价
            'customer_price' => $materialInfo['customer_price'], // 客户单价
            'customer_dosage' => 0, // 用量 目前直接使用 客户用量
            'fabric_width' => $materialInfo['fabric_width'],
            'fabric_width_once' => $materialInfo['fabric_width'],
            'weight' => $materialInfo['weight'],
            'weight_once' => $materialInfo['weight'],
            'material_dosage' => 0, // 米莫用量（首单取客户用量，返单优先取精准用量，没有精准用量再取最近5次裁床用量均值）
            'loss' => 0,
            'need_checkcloth' => $param['need_checkcloth'],
            'need_shrink' => $param['need_shrink'],
            'caigou_show' => 1,    // 是否在采购进度显示
            'create_time' => time(),
            'update_time' => time(),
        ];
        return db('order_material')->insertGetId($orderMaterial);
    }
}